package com.kura.uednews.ultilities;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import com.kura.uednews.dantri.NewsFeed;
import com.kura.uednews.dantri.DanTriHandler;
import com.kura.uednews.dantri.UedHandler;

import android.content.Context;
import android.util.Log;

public class FileIO {

	private final String FILENAME = "news_feed1.xml";
	private Context context = null;
	private DanTriHandler dtRssHandler;
	private UedHandler uedHandler;

	public FileIO(Context context) {
		this.context = context;
	}

	public void downloadFile(String link) {
		try {
			// get the URL
			URL url = new URL(link);
			Log.e("link", "-" + link + "-");

			// get the input stream
			InputStream in = url.openStream();

			// get the output stream
			FileOutputStream out = context.openFileOutput(FILENAME,
					Context.MODE_PRIVATE);

			// read input and write output
			byte[] buffer = new byte[1024];
			int bytesRead = in.read(buffer);
			while (bytesRead != -1) {
				out.write(buffer, 0, bytesRead);
				bytesRead = in.read(buffer);
			}
			out.close();
			in.close();
		} catch (IOException e) {
			Log.e("News reader", e.toString());
		}
	}

	public NewsFeed readFile(int type) {
		NewsFeed feed = null;
		Log.e("type", type + "");

		try {
			// get the XML reader
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser parser = factory.newSAXParser();
			XMLReader xmlreader = parser.getXMLReader();

			// set content handler
			// 1 UED
			// 2 DANTRI
			if (type == 1) {
				uedHandler = new UedHandler();
				xmlreader.setContentHandler(uedHandler);
			} else if (type == 2) {
				dtRssHandler = new DanTriHandler();
				xmlreader.setContentHandler(dtRssHandler);
			}

			// read the file from internal storage
			FileInputStream in = context.openFileInput(FILENAME);

			// parse the data
			InputSource is = new InputSource(in);
			xmlreader.parse(is);

			// set the feed in the activity
			if (type == 1) {
				feed = uedHandler.getFeed();
			}
			else if (type == 2) {
				feed = dtRssHandler.getFeed();
			}
			return feed;
		} catch (Exception e) {
			Log.e("News reader", e.toString());
			return null;
		}
	}
}